"""
Git提交历史爬虫模块
负责从Git仓库获取提交历史和代码差异
"""
from typing import List, Dict, Optional
import git
from datetime import datetime
import logging
from pathlib import Path

class GitCrawler:
    def __init__(self, repo_path: str, db_client=None):
        self.repo_path = repo_path
        self.repo = git.Repo(repo_path)
        self.db_client = db_client
        self.logger = logging.getLogger(__name__)

    def get_commit_history(self, since: Optional[datetime] = None) -> List[Dict]:
        """获取提交历史
        
        Args:
            since: 可选，获取指定日期之后的提交
            
        Returns:
            List[Dict]: 提交历史列表，每个提交包含以下信息：
                - commit_id: 提交ID
                - author: 作者
                - date: 提交日期
                - message: 提交信息
                - diff: 代码差异
        """
        commits = []
        for commit in self.repo.iter_commits():
            if since and commit.committed_datetime < since:
                continue
                
            commit_info = {
                'commit_id': commit.hexsha,
                'author': commit.author.name,
                'date': commit.committed_datetime,
                'message': commit.message,
                'diff': self._get_commit_diff(commit)
            }
            commits.append(commit_info)
            
        return commits

    def _get_commit_diff(self, commit) -> Dict:
        """获取某次提交的代码差异
        
        Args:
            commit: git.Commit对象
            
        Returns:
            Dict: 包含文件修改信息的字典
        """
        diff_info = {
            'files_changed': [],
            'insertions': 0,
            'deletions': 0
        }
        
        if not commit.parents:  # 首次提交
            return diff_info
            
        parent = commit.parents[0]
        for diff in parent.diff(commit):
            file_diff = {
                'file_path': diff.a_path,
                'change_type': diff.change_type,
                'diff_content': diff.diff.decode('utf-8', errors='ignore')
            }
            diff_info['files_changed'].append(file_diff)
            
        return diff_info

    def get_file_history(self, file_path: str) -> List[Dict]:
        """获取特定文件的修改历史
        
        Args:
            file_path: 文件路径
            
        Returns:
            List[Dict]: 文件的修改历史列表
        """
        file_history = []
        for commit in self.repo.iter_commits(paths=file_path):
            history_item = {
                'commit_id': commit.hexsha,
                'author': commit.author.name,
                'date': commit.committed_datetime,
                'message': commit.message
            }
            file_history.append(history_item)
            
        return file_history 